﻿using System;
using System.Data;
using System.IO;
using VoteMS.BLL;
using VoteMS.Model;

namespace VoteMS.UI
{
    public partial class Update : System.Web.UI.Page
    {
       private readonly ProjectsBLL  projectsBll = new ProjectsBLL();
       private readonly ProjectTypeBLL  projectTypeBll= new ProjectTypeBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    string pid = Request.QueryString["pid"].ToString();
                    //加载项目类别
                    DataTable dt = projectTypeBll.GetProjectType();
                    ddlTypeID.DataValueField = "TypeID";
                    ddlTypeID.DataTextField = "TypeName";
                    ddlTypeID.DataSource = dt;
                    ddlTypeID.DataBind();
                    //加载项目信息
                    ProjectModel model = projectsBll.GetProjectById(int.Parse(pid));
                    labelProjectID.Text = model.ProjectID + "";
                    txtProjectName.Text = model.ProjectName;
                    txtProjectDepart.Text = model.ProjectDepart;
                    txtProjectInfo.Text = model.ProjectInfo;
                    labelProjectNumber.Text = model.ProjectNumber + "";
                    labelProjectImg.Text = model.ProjectImage;
                    ddlTypeID.SelectedValue = model.TypeID+"";
                }
                catch (Exception)
                {
                     Response.Redirect("~/Default.aspx");
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ProjectModel project = new ProjectModel();
            project.ProjectID = int.Parse(labelProjectID.Text.Trim());
            project.ProjectName = txtProjectName.Text.Trim();
            project.TypeID = int.Parse(ddlTypeID.SelectedValue.Trim());
            project.ProjectDepart = txtProjectDepart.Text.Trim();
            /* project.ProjectImage =  string.IsNullOrEmpty(fileProjectImage.FileName)?labelProjectImg.Text.Trim():fileProjectImage.FileName;*/
            string oldImg = string.IsNullOrEmpty(fileProjectImage.FileName) ? labelProjectImg.Text.Trim() : fileProjectImage.FileName;
            project.ProjectImage = Guid.NewGuid().ToString() + Path.GetExtension(oldImg);
            string path = Server.MapPath("~/Content/Images/") + project.ProjectImage;
            fileProjectImage.SaveAs(path);
            project.ProjectInfo = txtProjectInfo.Text.Trim();
            string message = projectsBll.UpdateProject(project);
            string[] result = message.Split('|');
            Response.Write("<script>alert('" + result[0] + "');window.location.href='Default.aspx';</script>");
        }
    }
}